function checkIfLocal(str){
	if (typeof str != 'undefined' && str && str !== '' && str != "null"){
		return true;
	}
	return false;
}

function newXMLHttpRequest() {
    try{
        return new XMLHttpRequest();
    } catch(e) {
        try{
            return new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try{
                return new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                alert("Sorry, your browser doesn't support AJAX.");
                throw e;
            }
        }
    }
}

//读取用户信息
function getUser(uid, OAuth, accessor, accessToken, callback) {
	var requestStr = "?uid=" + uid;
    var message = {
        method: "get", action:accessor.serviceProvider.userInfoURL + requestStr
		 , parameters: [["scope", "http://www.google.com/m8/feeds/"]]
    };
    var requestBody = OAuth.formEncode(message.parameters);
    var request = newXMLHttpRequest();

    request.onreadystatechange = function receiveData() {
        if (request.readyState == 4) {
			if (request.status == 200){
				try{
					var results = request.responseText;
					callback(results);
				}catch(e){}
			}
        }
    };
	
    request.open(message.method, message.action, true); 
    request.setRequestHeader("Authorization", "OAuth2 " + accessToken);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send(requestBody);
}

function formatCount(count){
	if(count > 100000){
		var count = Math.floor(count / 10000) + "万";
	}
	return count;
}

function formatGender(gender){
	if(gender == "m"){
		var gender = "男";
	} else if(gender == "f") {
		var gender = "女";
	} else {
		var gender = "未知";
	}
	return gender;
}

function searchAtLink(str){
	var regAtName = /@[^@\s\:\.\,，。：、)）]+/ig; 
	var atMatchList = str.match(regAtName);
	//alert(atMatchList);
	if(atMatchList != null && atMatchList != undefined){
		for(k in atMatchList){
			var reg = new RegExp("([^>]*)(" + atMatchList[k] + ")");
			str = str.replace(reg,"$1<screen_name>$2</screen_name><span></span>");
		}
	}
	return str;
}

function searchTinyLink(str){
	var re = /http:\/\/[a-bA-Z0-9\.\/]+/ig; 
	var matchList = str.match(re);
	//alert(atMatchList);
	if(matchList != null && matchList != undefined){
		for(k in matchList){
			str = str.replace(matchList[k],"<tinylink>" + matchList[k] + "</tinylink>");
		}
	}
	return str;
}


//计算字符串长度  
function strlen(str) {  
	var len = 0;  
	for (var i = 0; i < str.length; i++) {  
		if (str.charCodeAt(i) > 255 || str.charCodeAt(i<0)) len += 2; else len ++;  
	}  
	 return len;  
}

function showHideLoading(type){
	if(type == 1){
		$(".loading").fadeIn();
	} else{
		$(".loading").hide();
	}
}


//搜索模块
function search(){
	$("#keyword").focus(function(){
		if($(this).val() == "搜索微博、找人") {
			$(this).val("");
		} else {
			$(this).select();
		}
	});
	
	$("#keyword").blur(function(){
		if($(this).val() == "") {
			$(this).val("搜索微博、找人");
		}
	});
	$("#btn_search").click(function(){
		var keyword = encodeURIComponent($("#keyword").val());
		var sURL = "http://s.weibo.com/weibo/" + keyword;
		createNewTab(sURL);
	});
	$("#keyword").keydown(function(e){
		if(e.keyCode == 13) {
			var keyword = encodeURIComponent($("#keyword").val());
			var sURL = "http://s.weibo.com/weibo/" + keyword;
			createNewTab(sURL);
		}
	});
}

//显示更新信息
function showUnreadInfo(results){
	if(results["status"]>0){
		newWeibo = 1;
		$("#new_weibo b").html(results["status"]);
		$("#new_weibo b").fadeIn();
	} 
	
	if(results["followers"]>0){	
		$("#new_fans b").html(results["followers"]);
		$("#new_fans b").fadeIn();
	}

	if(results["comments"]>0){	
		$("#new_comment b").html(results["comments"]);
		$("#new_comment b").fadeIn();
	}
	
	if(results["mentions"]>0){
		$("#new_atme b").html(results["mentions"]);
		$("#new_atme b").fadeIn();
	}

	if(results["dm"]>0){	
		$("#new_msg b").html(results["dm"]);
		$("#new_msg b").fadeIn();
	}
	
}

//数据加载界面
function showDataLoading(){
	$(".loadingbar").remove();
	var html = "<div class='loadingbar'><img src='images/loading.gif' />正在加载...</div>";
	$("#content").prepend(html);
}
function removeDataLoading(){
	$(".loadingbar").animate({opacity:0},300,"linear",function(){$(".loadingbar").remove();});
}

//微博图片浏览
function loadWeiboPic(ele){
	var picHtml = "<img src='images/loading.gif' class='imgloading' style='position:absolute;left:10px;top:10px;z-index:888;' />";
	$(ele + " .weibo_pic").click(function(){
		var ele = $(this);
		var oWidth = ele.width();
		var oHeight = ele.height();
		var oPic = ele.attr("src");
		var nPic = ele.attr("nPic")
		ele.attr("width", oWidth);
		if(oPic.indexOf("thumbnail") > 0){
			ele.parent(".weibopic").prepend(picHtml);
			ele.prev(".imgloading").css("left", (oWidth/2 - 8)+"px");
			ele.prev(".imgloading").css("top", (oHeight/2 - 8)+"px");
			var currentImgType = "thumb";
		} else {
			var currentImgType = "mid";
			var nWidth = ele.attr("nWidth");
			ele.attr("src", nPic);
			ele.attr("nPic", oPic);
			ele.attr("nWidth", oWidth);
			ele.animate({width:nWidth},300,"linear",function(){ele.next(".weibopic_bar").hide();});
			return;
		}

		if(!ele.parent().children(".temppic").attr("src")){
			var tempPic = "<img src='" + nPic + "' style='display:none' class='temppic' />";
			ele.parent().append(tempPic);
		} else {
			ele.prev(".imgloading").remove();
			var nWidth = ele.attr("nWidth");
			ele.attr("src", nPic);
			ele.attr("nPic",oPic);
			ele.attr("nWidth", oWidth);
			ele.animate({width:nWidth},300,"linear",function(){
				ele.next(".weibopic_bar").fadeIn();
			});
		}
		
		ele.parent().children(".temppic").load(function(){
			ele.prev(".imgloading").remove();
			ele.attr("src", nPic);
			ele.attr("nPic",oPic);
			ele.attr("nWidth", oWidth);
			var newWidth = ($(this).width() > 330) ? 330 : $(this).width();		
			ele.animate({width:newWidth},300,"linear",function(){
				ele.next(".weibopic_bar").fadeIn();
			});
		});
	});
}

//缓存系统
var WeiboCache; if (WeiboCache == null) WeiboCache = {};

WeiboCache.setProperties = function setProperties(into, from) {
    if (into != null && from != null) {
        for (var key in from) {
            into[key] = from[key];
        }
    }
    return into;
}

WeiboCache.setProperties(WeiboCache,{
	setCache:function(key, val, cacheTime){
		var timeStamp = new Date().getTime() / 1000;
		var cacheData = {
			"val":val,
			"cachetime":cacheTime,
			"timestamp":timeStamp
		};
		var cacheStr = JSON.stringify(cacheData);
		localStorage.setItem(key, cacheStr);
	},

	getCache:function(key){
		var cacheStr = localStorage.getItem(key);
		if(!checkIfLocal(cacheStr)){
			return false;
		}
		try{
			var cacheData = JSON.parse(cacheStr);
		} catch(e){
			var cacheData = eval("(" + cacheStr + ")");
		}
		if(cacheData){
			var cTime = new Date().getTime() / 1000;
			if(parseInt(cTime) - parseInt(cacheData["timestamp"])< parseInt(cacheData["cachetime"]) ){
				var valStr = cacheData["val"];
				try{
					cacheData["val"] = JSON.parse(valStr);	
				}catch(e){
					cacheData["val"] = eval("(" + valStr + ")");
				}
				return cacheData;
			} else {
				return false;
			}
		}else {
			return false;
		}
	}
});

function formatDatetime(timestamp){
	var dt = new Date();
	var currentTimestamp = parseInt(dt.getTime());
	//计算当前到今天零点有多少秒
	var cHour = dt.getHours();
	var cMin = dt.getMinutes();
	var cSec = dt.getSeconds();
	var interval1 = (cHour*60*60 + cMin*60 + cSec)*1000;
	var interval2 = parseInt(interval1 + 24*3600*1000);
	var t = new Date(parseInt(timestamp*1000));
	if((currentTimestamp - timestamp*1000) < interval1){
		var day = "今天";
	}else if((currentTimestamp - timestamp*1000) >= interval1 && (currentTimestamp - timestamp*1000) < interval2 ){
		var day = "昨天";
	} else {
		var day = (t.getMonth() + 1) + "月" + t.getDate() + "日";
	}
	var h = parseInt(t.getHours());
	h = (h < 10) ? "0" + h : h;
	var m = parseInt(t.getMinutes());
	m = (m < 10) ? "0" + m : m;
	var time = h + ":" + m;
	return day + " " + time;
}

function deleteEleFromDict(key, dict){
	var newDict = {}
	for(k in dict){
		if(key != k){
			newDict[k] = 1;
		}
	}
	return newDict;
}